package uk.ac.ok.cs.diadem.oxpath.worker.functions;


import java.util.HashMap;

import org.gearman.GearmanFunction;
import org.gearman.GearmanFunctionCallback;

import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;

import uk.ac.ox.cs.diadem.oxpath.server_distributed.gearman.functions.MessagesSenderImpl;
import uk.ac.ox.cs.diadem.oxpath.server_distributed.messages.TaskDescriptionMessage.TaskInfo;
import uk.ac.ox.cs.diadem.oxpath.server_distributed.utils.ByteConverterUtils;


/**
 * 
 * Example of Gearman function that receives a string parameter and returns an upper case string.
 * 
 * 
 * @author Salvatore Toscano
 * 
 */
public class UpperCaseRemoteFunction extends MessagesSenderImpl implements GearmanFunction {
	
	@Override
	public byte[] work(String function, byte[] data, GearmanFunctionCallback callback)
			throws Exception {

		TaskInfo informationTask=null;
		String str=null;

		try {
			
			LOGGER.info("executing function {}",UpperCaseRemoteFunction.class);
			
			informationTask = TaskInfo.parseFrom(data);

			if(informationTask.getMapParameters().getItemsCount() == 1){
				try {
					
					ByteString tmp = getParametersByKey(informationTask,STRING_PARAMETER);
					
					if(tmp != null)
					{
						//retrieve parameter
						str = (String) ByteConverterUtils.deserialize(tmp.toByteArray());
					}
					else
					{
						sendMessageWithErrors(callback, informationTask, new HashMap<String, Object>(), "Missing or wrong parameters");
						throw new Exception("Missing or wrong parameters");
					}
					

				} catch (Exception e) {

					sendMessageWithErrors(callback, informationTask, new HashMap<String, Object>(), "Error parameters: "+e.toString());
					throw new Exception(e);
				}

				str = str.toUpperCase();
			}
			else 
			{
				sendMessageWithErrors(callback, informationTask, new HashMap<String, Object>(), "Missing parameters");
				throw new Exception();
			}


		} catch (InvalidProtocolBufferException e) {
			sendMessageWithErrors(callback, informationTask, new HashMap<String, Object>(), e.toString());
			throw new Exception();
		}

		return createResultMessage(informationTask, new HashMap<String, Object>(), str.getBytes());
	}

}
